/*
 * Copyright 2013 University of Padua, Italy
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.dei.unipd.healthservice.database;

import it.dei.unipd.healthservice.resource.*;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

/**
 * Aggiorna i dati di un fornitore
 * @author Giorgio Vitale
 * @version 1.00
 */
public class UpdateFornitoreDatabase {
	protected final String STATEMENT_UPDATE ="UPDATE fornitore SET ragionesociale=?, "+
					"mail=?, tel=?, stato=?, provincia=?, indirizzo=?, " +
					"cap=?, citta=? WHERE piva=?;";
	
	/**
	 * Connessione al database
	 */
	private final Connection con;

	/**
	 * Fornitore da modificare
	 */
	private final Fornitore fornitore;
	
	/**
	 * Modifica il fornitore
	 * @param con
	 *            connessione al database.
	 * @param fornitore fornitore da modificare, con i dati aggiornati
	 */
	public UpdateFornitoreDatabase(Connection con, Fornitore fornitore) {
		this.con = con;
		this.fornitore = fornitore;
	}

	/**
	 * Aggiorna i dati del fornitore
	 * @throws SQLException
	 *             in caso di problemi nell'accesso al database.
	 */
	public void update() throws SQLException {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = con.prepareStatement(STATEMENT_UPDATE);
			pstmt.setString(1, fornitore.getRagioneSociale());
			pstmt.setString(2, fornitore.getMail());
			pstmt.setString(3, fornitore.getTel());
			pstmt.setString(4, fornitore.getStato());
			pstmt.setString(5, fornitore.getProvincia());
			pstmt.setString(6, fornitore.getIndirizzo());
			pstmt.setString(7, fornitore.getCap());
			pstmt.setString(8, fornitore.getCitta());
			pstmt.setString(9, fornitore.getPiva());
			pstmt.executeUpdate();
		}
		finally {
			if (rs != null)
				rs.close();
			if (pstmt != null)
				pstmt.close();
			con.close();
		}
	}
}
